<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        img {
            width: 200px;
            height: 200px;
        }

        span {
            margin-right: 10px;
        }

        li {
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <h1>购物车</h1>
    <ul>

    </ul>
    <h1>总价：<span class="money" style="color: red;">0</span>元</h1>
    <button onclick="suan()">结算</button>
    <script>
        var sp = JSON.parse(localStorage.getItem('shangp'))
        var ul = document.querySelector('ul')

        function fn() {
            ul.innerHTML = ''
            sp.forEach(item => {
                ul.innerHTML += `
            <li>
                <input type="checkbox" ${item.is ? 'checked' : ''} onclick="dan(${item.id})">
                <img src="${item.img}">
                <span>名称：${item.name}</span>
                <span>价格：${item.price}</span>
                <button onclick='jian(${item.id})'>-</button>
                <span>1</span>
                <button onclick='jia(${item.id})'>+</button>
            </li>`
            })
        }
        fn()

        // 数量加减
        function jia(id) {
            var a = sp.findIndex(item => item.id == id)
            var b = sp[a].num++ + 1
            event.target.previousElementSibling.innerHTML = b
        }

        function jian(id) {
            var a = sp.findIndex(item => item.id == id)
            if (sp[a].num != 0) {
                var b = sp[a].num-- - 1
            }
            event.target.nextElementSibling.innerHTML = b
        }

        // 勾选计算价格
        var inps = document.querySelectorAll('input')
        function dan(id) {
            var a = sp.findIndex(item => item.id == id)
            sp[a].is = event.target.checked
            var zong = 0
            sp.forEach(item => {
                if (item.is) {
                    zong += item.price * item.num
                }
            })
            document.querySelector('.money').innerHTML = zong
        }

        // 结算
        function suan() {
            var all = []
            sp.forEach(item => {
                if (item.is) {
                    all.push(item)
                    localStorage.setItem('all', JSON.stringify(all))
                    location.assign('./结算.html')
                }
            })
        }
    </script>
</body>

</html>